<!-- 编辑题目 -->
<template>
  <el-dialog
    :title="dialogTitle"
    :visible.sync="visible"
    width="800px"
    @close="resetForm"
    :close-on-click-modal="false"
  >
    <!-- 题型切换 -->
    <div class="question-type-tabs">
      <el-button
        v-for="type in questionTypes"
        :key="type.value"
        :type="formData.questionType === type.value ? 'primary' : 'default'"
        @click="switchQuestionType(type.value)"
        size="small"
        :disabled="isEditMode"
      >
        {{ type.label }}
      </el-button>
    </div>

    <!-- 题干 -->
    <el-form ref="form" :model="formData" :rules="rules" label-width="80px">
      <el-form-item label="题干" prop="questionText">
        <el-input
          v-model="formData.questionText"
          type="textarea"
          :autosize="{ minRows: 3, maxRows: 5 }"
          placeholder="请输入题目内容"
        />
      </el-form-item>

      <!-- 选项区域 -->
      <el-form-item
        label="选项"
        :prop="formData.questionType === 'multiple' ? 'answers' : 'answer'"
      >
        <div class="options-container">
          <!-- 单选题和多选题 -->
          <template v-if="formData.questionType !== 'judge'">
            <div
              v-for="(option, index) in currentOptions"
              :key="option.label"
              class="option-item"
            >
              <div class="option-label">
                <el-radio
                  v-if="formData.questionType === 'single'"
                  v-model="formData.answer"
                  :label="option.label"
                  class="option-radio"
                >
                  {{ option.label }}
                </el-radio>
                <el-checkbox
                  v-else-if="formData.questionType === 'multiple'"
                  v-model="formData.answers"
                  :label="option.label"
                  class="option-checkbox"
                >
                  {{ option.label }}
                </el-checkbox>
              </div>

              <el-input
                v-model="option.value"
                type="textarea"
                :autosize="{ minRows: 1, maxRows: 3 }"
                placeholder="请输入选项内容"
                class="option-input"
              />

              <div class="option-actions">
                <el-button
                  size="mini"
                  type="danger"
                  @click="removeOption(index)"
                  :disabled="currentOptions.length <= 2"
                >
                  删除
                </el-button>
              </div>
            </div>

            <!-- 新增选项按钮 -->
            <el-button
              size="small"
              type="primary"
              @click="addOption"
              class="add-option-btn"
            >
              新增选项
            </el-button>
          </template>

          <!-- 判断题 -->
          <div v-else class="judge-options">
            <el-radio-group v-model="formData.answer">
              <el-radio label="对">对</el-radio>
              <el-radio label="错">错</el-radio>
            </el-radio-group>
          </div>
        </div>
      </el-form-item>

      <!-- 答案解析 -->
      <el-form-item label="答案解析" prop="analysis">
        <el-input
          v-model="formData.analysis"
          type="textarea"
          :autosize="{ minRows: 3, maxRows: 5 }"
          placeholder="请输入答案解析"
        />
      </el-form-item>
    </el-form>

    <div slot="footer" class="dialog-footer">
      <el-button @click="cancel">取消</el-button>
      <el-button type="primary" @click="submit">提交</el-button>
    </div>
  </el-dialog>
</template>

<script>
export default {
  name: "EditQuestionDialog",
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    questionData: {
      type: Object,
      default: () => ({}),
    },
  },
  data() {
    return {
      dialogTitle: "编辑题目",
      formData: {
        questionId: null,
        questionText: "",
        questionType: "single",
        answer: "", // 单选或判断的答案
        answers: [], // 多选答案
        singleOptions: [
          { label: "A", value: "" },
          { label: "B", value: "" },
          { label: "C", value: "" },
          { label: "D", value: "" },
        ],
        multipleOptions: [
          { label: "A", value: "" },
          { label: "B", value: "" },
          { label: "C", value: "" },
          { label: "D", value: "" },
        ],
        analysis: "",
      },
      rules: {
        questionText: [
          { required: true, message: "请输入题干", trigger: "blur" },
        ],
        answer: [{ required: true, message: "请选择答案", trigger: "change" }],
        answers: [
          {
            type: "array",
            required: true,
            message: "请至少选择2个答案",
            trigger: "change",
          },
        ],
        analysis: [
          { required: false, message: "请输入答案解析", trigger: "blur" },
        ],
      },
      questionTypes: [
        { label: "单选题", value: "single" },
        { label: "多选题", value: "multiple" },
        { label: "判断题", value: "judge" },
      ],
    };
  },
  computed: {
    currentOptions() {
      return this.formData.questionType === "single"
        ? this.formData.singleOptions
        : this.formData.questionType === "multiple"
        ? this.formData.multipleOptions
        : [];
    },
    isEditMode() {
      return !!this.formData.questionId;
    },
  },
  watch: {
    questionData: {
      handler(newVal) {
        if (newVal && Object.keys(newVal).length > 0) {
          this.initFormData(newVal);
        }
      },
      immediate: true,
      deep: true,
    },
  },
  methods: {
    initFormData(data) {
      // 初始化表单数据
      this.formData.questionId = data.questionId;
      this.formData.questionText = data.questionName;
      this.formData.analysis = data.analysisContent || "";

      // 设置题型
      const typeMap = { 1: "single", 2: "multiple", 3: "judge" };
      this.formData.questionType = typeMap[data.questionType] || "single";

      // 处理选项和答案
      if (this.formData.questionType === "single") {
        this.processSingleChoice(data);
      } else if (this.formData.questionType === "multiple") {
        this.processMultipleChoice(data);
      } else {
        this.processJudge(data);
      }
    },

    processSingleChoice(data) {
      // 解析单选题选项
      this.populateOptionsFromList(data);
      this.formData.answer = data.answer || "";
    },

    processMultipleChoice(data) {
      // 解析多选题选项
      this.populateOptionsFromList(data);
      this.formData.answers = data.answer ? data.answer.split(",") : [];
    },
    // 从 questionOptionList 填充选项
    populateOptionsFromList(data) {
      // 重置选项数组
      this.formData.singleOptions = [];
      this.formData.multipleOptions = [];

      if (data.questionOptionList && Array.isArray(data.questionOptionList)) {
        // 根据选项列表填充选项
        data.questionOptionList.forEach((option, index) => {
          const optionItem = {
            label: option.optionName,
            value: option.optionContent || "",
          };

          // 同时填充单选和多选选项数组（因为切换题型时需要）
          this.formData.singleOptions.push(optionItem);
          this.formData.multipleOptions.push(optionItem);
        });
      }

      // 确保至少有4个选项
      this.ensureMinimumOptions();
    },
    // 确保选项数组至少有4个选项
    ensureMinimumOptions() {
      const minLength = 4;

      // 补充单选选项
      while (this.formData.singleOptions.length < minLength) {
        this.formData.singleOptions.push({
          label: String.fromCharCode(65 + this.formData.singleOptions.length),
          value: "",
        });
      }

      // 补充多选选项
      while (this.formData.multipleOptions.length < minLength) {
        this.formData.multipleOptions.push({
          label: String.fromCharCode(65 + this.formData.multipleOptions.length),
          value: "",
        });
      }
    },
    processJudge(data) {
      // 解析判断题
      this.formData.answer = data.answer || "";
    },

    resetForm() {
      this.$refs["form"].resetFields();
      this.formData = {
        questionId: null,
        questionText: "",
        questionType: "single",
        answer: "",
        answers: [],
        singleOptions: [
          { label: "A", value: "" },
          { label: "B", value: "" },
          { label: "C", value: "" },
          { label: "D", value: "" },
        ],
        multipleOptions: [
          { label: "A", value: "" },
          { label: "B", value: "" },
          { label: "C", value: "" },
          { label: "D", value: "" },
        ],
        analysis: "",
      };
      this.$emit("update:visible", false);
    },

    addOption() {
      const optionsArray =
        this.formData.questionType === "single"
          ? this.formData.singleOptions
          : this.formData.multipleOptions;

      const newLabel = String.fromCharCode(65 + optionsArray.length);
      const newOption = {
        label: newLabel,
        value: "",
      };

      if (this.formData.questionType === "single") {
        this.formData.singleOptions.push(newOption);
        // 同步到多选数组
        this.formData.multipleOptions.push({ ...newOption });
      } else if (this.formData.questionType === "multiple") {
        this.formData.multipleOptions.push(newOption);
        // 同步到单选数组
        this.formData.singleOptions.push({ ...newOption });
      }
    },

    removeOption(index) {
      if (this.formData.questionType === "single") {
        const removedLabel = this.formData.singleOptions[index].label;
        this.formData.singleOptions.splice(index, 1);
        // 同步删除多选数组中的对应项
        const multiIndex = this.formData.multipleOptions.findIndex(
          (opt) => opt.label === removedLabel
        );
        if (multiIndex !== -1) {
          this.formData.multipleOptions.splice(multiIndex, 1);
        }
        // 更新剩余选项标签
        this.updateRemainingOptionLabels(this.formData.singleOptions);
      } else if (this.formData.questionType === "multiple") {
        const removedLabel = this.formData.multipleOptions[index].label;
        this.formData.multipleOptions.splice(index, 1);
        // 同步删除单选数组中的对应项
        const singleIndex = this.formData.singleOptions.findIndex(
          (opt) => opt.label === removedLabel
        );
        if (singleIndex !== -1) {
          this.formData.singleOptions.splice(singleIndex, 1);
        }
        // 更新剩余选项标签
        this.updateRemainingOptionLabels(this.formData.multipleOptions);
      }
    },
    // 更新剩余选项标签
    updateRemainingOptionLabels(options) {
      options.forEach((option, index) => {
        option.label = String.fromCharCode(65 + index);
      });
    },
    switchQuestionType(type) {
      // 保存当前选项数据
      const currentSingleOptions = [...this.formData.singleOptions];
      const currentMultipleOptions = [...this.formData.multipleOptions];

      this.formData.questionType = type;

      // 清空当前答案
      if (type === "single" || type === "judge") {
        this.formData.answer = "";
      } else {
        this.formData.answers = [];
      }

      // 恢复选项数据
      this.formData.singleOptions = currentSingleOptions;
      this.formData.multipleOptions = currentMultipleOptions;
    },

    cancel() {
      this.$emit("update:visible", false);
      this.resetForm();
    },

    submit() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          // 动态构建选项数据
          const options =
            this.formData.questionType === "single"
              ? this.formData.singleOptions
              : this.formData.multipleOptions;

          const questionData = {
            questionId: this.formData.questionId,
            questionName: this.formData.questionText,
            questionType:
              this.formData.questionType === "single"
                ? 1
                : this.formData.questionType === "multiple"
                ? 2
                : 3,
            answer:
              this.formData.questionType === "multiple"
                ? this.formData.answers.join(",")
                : this.formData.answer,
            analysisContent: this.formData.analysis,
            exampleOne: options[0]?.value || "",
            exampleTwo: options[1]?.value || "",
            exampleThree: options[2]?.value || "",
            exampleFour: options[3]?.value || "",
          };

          this.$emit("submit", questionData);
          this.cancel();
        }
      });
    },
  },
};
</script>

<style scoped>
.question-type-tabs {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
}

.options-container {
  margin-top: 10px;
}

.option-item {
  display: flex;
  align-items: flex-start;
  margin-bottom: 10px;
  gap: 10px;
}

.option-label {
  width: 50px;
  display: flex;
  align-items: center;
  padding-top: 6px;
}

.option-item .el-input {
  flex: 1;
}

.option-actions {
  padding-top: 6px;
}

.judge-options {
  margin-top: 10px;
}
</style>